﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
//using System.Windows.Forms;
using System.Windows.Controls;
using System.Drawing;
using WCintiqHID;
using clrWIntuosHID;
using Treblotto_TabletDefs;
using WindowsInput;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.Resources;
using System.Windows.Interop;
using System.Text;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using System.Diagnostics;
using Windows.UI.Notifications;
using Windows.UI.Popups;
using Windows.Data.Xml.Dom;
using TTIServer.TTISettings.Pages;
namespace TTIServer
{

	

		public partial class TTIServerClass : System.Windows.Application
		{

			public const byte MaxTablets = 8;
			public static string appID = "TTIServer";

			ToastNotificationHelper TTIToastNotifier = new ToastNotificationHelper(appID);

			System.Windows.Forms.NotifyIcon TTINotify;
			System.Windows.Forms.ContextMenu ContextMenuTTI;

			//List of the Connected Wacom Devices.
			List<WCintiqHID.Cintiq> CintiqList = new List<Cintiq>(1);
			List<clrWIntuosHID.Intuos> IntuosList = new List<clrWIntuosHID.Intuos>(1);
			List<TTIServer.T3DC.EMRDevice> ProxedInDevices = new List<TTIServer.T3DC.EMRDevice>(20);

			private static byte LED_L = 0x5;
			private static byte LED_R = 0x6;

			//MIDI Devices



			private double OldActualHeight = 0.0;
			String ContextString;
			private TTIServer.T3DC.TreblottoDigitizerDataDataContext myTD3C;// = new TreblottoDigitizerDataDataContext("Data Source=STUDIOPC\\TTIDB;Initial Catalog=WCISettings;Integrated Security=True");
			RotationMenu myRotationMenu;// = new RotationMenu();
			//RotationMenu myRotationMenu;
			//multiple Cintiqs?

			//The below variables become Arrays, and before I do operations, I get the 'current' Cintiq

			private TabletSettings[] LoadedTablets = new TabletSettings[MaxTablets];



			private CintiqSettingsCollection AllCintiqSettings;


			private WCintiqHID.Cintiq_K wc21ux;// = new WCintiqHID.Cintiq_K();
			private WCintiqHID.Cintiq_K wc24hd;
			private WCintiqHID.Cintiq_K wc22hd;
			private WCintiqHID.Cintiq_K wc13hd;

			private List<EMRDevice> K_Styli;

			private ExpressKeySettings w21uxEKS;
			private ExpressKeySettings w22hdEKS;
			private ExpressKeySettings w24hdEKS;
			private ExpressKeySettings w13hdEKS;

			//These should be in the ExpressKeysSettings Class
			private System.Windows.Controls.Button[,] EKLabels;  //The Labels ARE buttons... OKAY, I'll change the Variable Name.  Sheesh.
			private System.Windows.Controls.Button[,] EKLabels_2400;  //The Labels ARE buttons... OKAY, I'll change the Variable Name.  Sheesh.
			private System.Windows.Controls.Button[,] EKLabels_2200;
			private System.Windows.Controls.Button[,] EKLabels_1300;


			private clrWIntuosHID.WIntuos4 wi4s = new clrWIntuosHID.WIntuos4();
			private clrWIntuosHID.WIntuos4 wi4m = new clrWIntuosHID.WIntuos4();
			private clrWIntuosHID.WIntuos4 wi4l = new clrWIntuosHID.WIntuos4();
			private clrWIntuosHID.WIntuos4 wi4xl = new clrWIntuosHID.WIntuos4();

			TTIServer.TTISettings.MainWindow myMainWindow;

			private ExpressKeySettings wI4EKS = new ExpressKeySettings(0xBA);

			private System.Timers.Timer epTimer;
			private WCintiqHID.ScreenFactorClass mySF = new WCintiqHID.ScreenFactorClass();

			private int LastRotationAngle = -1;

			bool[] GroupButtonArmed;
			bool PenRotationEnabled = false;

			//Momentary DATA LUT?
			// 804 = Pen Rotation
			private delegate void ImageUpdateDelegete(String WhichPen);

			public class EMRDevicesEqual : IEqualityComparer<TTIServer.T3DC.EMRDevice>
			{

				public bool Equals(TTIServer.T3DC.EMRDevice X, TTIServer.T3DC.EMRDevice Y)
				{

					if ((X.PenID.Equals(Y.PenID)) && (X.SerialNum.Equals(Y.SerialNum)))
						return true;
					else
						return false;
				}

				public int GetHashCode(TTIServer.T3DC.EMRDevice obj)
				{
					return obj.ToString().ToLower().GetHashCode();
				}

			}

			//TODO: Add a subroutine which starts the appropriate animations
			// regardless of whether a Cintiq or Intuos is showing.

			[DllImport("User32.dll")]
			static extern IntPtr GetForegroundWindow();

			[DllImport("user32.dll")]
			static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

			private string GetActiveWindowTitle()
			{

				const int nChars = 256;
				IntPtr myHandle = IntPtr.Zero;
				StringBuilder buff = new StringBuilder(nChars);
				myHandle = GetForegroundWindow();

				if (GetWindowText(myHandle, buff, nChars) > 0)
				{
					return buff.ToString();
				}
				return null;

			}



			public TTIServerClass()
			{
				
//				Microsoft.Win32.SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged);


				ContextString = String.Format("Data Source={0}\\TTIDB;Initial Catalog=WCISettings;Integrated Security=True",System.Environment.MachineName);

				myTD3C = new TTIServer.T3DC.TreblottoDigitizerDataDataContext(ContextString);

				w21uxEKS = new ExpressKeySettings();

				IQueryable<TTIServer.T3DC.EMRDevice> myEMRDevices = from PenID in myTD3C.EMRDevices
											  select PenID;

				

				ContextMenuTTI = new System.Windows.Forms.ContextMenu();

				List<String> stopLabels = new List<String>();

				stopLabels.Add("Whole\nNote");
				stopLabels.Add("Half\r\nNote");
				stopLabels.Add("Quarter\r\nNote");
				stopLabels.Add("Eighth\r\nNote");
				stopLabels.Add("Sixteenth\r\nNote");
				stopLabels.Add("Thirty-Second\r\nNote");

				//w21uxEKS.ReadExpressKeySettings();


				myRotationMenu = new RotationMenu(stopLabels.Count, stopLabels);

				//ContextMenu.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 0));
				//ContextMenu.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));

				System.Windows.Forms.MenuItem OpenSettingsMenu = new System.Windows.Forms.MenuItem();

				OpenSettingsMenu.Text = "Open Tablet Control Panel";
				OpenSettingsMenu.Click += new System.EventHandler(OpenSettingsMenu_Select);
				OpenSettingsMenu.Index = 0;

				System.Windows.Forms.MenuItem ExitServer = new System.Windows.Forms.MenuItem();
				ExitServer.Text = "Exit TTI Server";
				ExitServer.Click += new System.EventHandler(this.ExitServer_Select);

				

				System.Windows.Forms.MenuItem NoAttachedTablets = new System.Windows.Forms.MenuItem();
				NoAttachedTablets.Text = "No Attached Tablets";
				NoAttachedTablets.Enabled = false;
				


				//OpenSettingsMenu.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0,0,0));
				//OpenSettingsMenu.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));

				ContextMenuTTI.MenuItems.Add(OpenSettingsMenu);
				ContextMenuTTI.MenuItems.Add(ExitServer);
				ContextMenuTTI.MenuItems.Add("-");
				

				TTINotify = new System.Windows.Forms.NotifyIcon();
				TTINotify.Icon = new System.Drawing.Icon("MainIcon.ico");
				TTINotify.Visible = true;



				TTINotify.DoubleClick += new System.EventHandler(TTINotify_DoubleClick);
				TTINotify.ContextMenu = ContextMenuTTI;

				
				Tablet_Factory TTInit = new Tablet_Factory();
				List<WCintiqHID.Cintiq_K> attachedCintiqs;

				AllCintiqSettings = CintiqSettinsCollectionLoader.LoadTTISettings();




				attachedCintiqs = TTInit.Init();


				if (attachedCintiqs == null)  //This needs to turn into a generic initialize statement, and based on what's returned
				//Build grab the expresskeys list.
				{
					ContextMenuTTI.MenuItems.Add(NoAttachedTablets);


				}
				else
				{
					//for each in attachedCintiqs
					ushort PID;
			//		CintiqGlobalGroup.IsEnabled = true;

					int TabletIndex = 0;  //Assign each tablet an ID for this session so that each tablet can be connected.


					foreach (Cintiq_K aCintiq in attachedCintiqs)
					{
						TabletSettings CurrentTablet = new TabletSettings();
						PID = aCintiq.GetPID();
						switch (PID)
						{

							case 0xCC:

								//Determine if we already have the 21UX in the Stored Settings
								//w21uxEKS.ReadExpressKeySettings(); //Which Settings?!
								LoadedTablets[TabletIndex] = AllCintiqSettings.GetTabletSettingsForPID(PID);

								if (LoadedTablets[TabletIndex] == null)
								{
									//Initialize Tablet
									CurrentTablet = DefaultTabletSettings.GetDefaultTabletSettings();
									CurrentTablet.ModelNumber = "DTK-2100";
									CurrentTablet.Name = "Cintiq 21UX Gen. 2";
									CurrentTablet.PID = PID;
									CurrentTablet.TabletID = TabletIndex++;

									//Initialize ExpressKeys
									w21uxEKS = new ExpressKeySettings(0xCC);
									w21uxEKS.Initialize(false);
									K_Styli = new List<EMRDevice>(1);
									CurrentTablet.SetCintiqButtonSettings(w21uxEKS);
									CurrentTablet.SetCurrentPenSettings(K_Styli);
									LoadedTablets[TabletIndex] = CurrentTablet;
									
								}

								

								wc21ux = aCintiq;

								//Initialize Event Handlers
								wc21ux.ExpressKeyEvent += new WCintiqHID.Cintiq_K.ExpressKeyHandler(OnExpressKeyEvent);
								wc21ux.ExpressPadEvent += new WCintiqHID.Cintiq_K.ExpressPadHandler(OnExpressPadEvent);
								wc21ux.PenRotateEvent += new WCintiqHID.Cintiq_K.PenRotationHandler(OnPenRotationEvent);
								wc21ux.PenProxInEvent += new WCintiqHID.Cintiq_K.PenProxInHandler(OnPenProxInEvent);
								wc21ux.PenProxOutEvent += new WCintiqHID.Cintiq_K.PenProxOutHandler(OnPenProxOutEvent);
								wc21ux.PenRotateEventWithAngle += new WCintiqHID.Cintiq_K.PenCurrentRotationAngleHandler(OnPenRotationValueEvent);
								w21uxEKS = LoadedTablets[TabletIndex].GetCintiqButtonSettings();
								K_Styli = LoadedTablets[TabletIndex].GetPensProxedIn();

								if (K_Styli == null)
								{

									K_Styli = new List<EMRDevice>(1);
									LoadedTablets[TabletIndex].SetCurrentPenSettings(K_Styli);
								}

								CurrentTablet.SetCintiqReference(wc21ux);
								CurrentTablet.SetCintiqButtonSettings(w21uxEKS);
								CurrentTablet.SetCurrentPenSettings(K_Styli);
								EKLabels = new System.Windows.Controls.Button[2, 8];

								System.Windows.Forms.MenuItem DTK2100 = new System.Windows.Forms.MenuItem("Cintiq 21UX (DTK-2100)");
								System.Windows.Forms.MenuItem DTK2100Extras = new System.Windows.Forms.MenuItem("Disable Tablet Input");
								System.Windows.Forms.MenuItem DTK2100Extras2 = new System.Windows.Forms.MenuItem("Diagnostics");
								GroupButtonArmed = new bool[] {true, true};

								DTK2100.MenuItems.Add(DTK2100Extras);
								DTK2100.MenuItems.Add(DTK2100Extras2);
								ContextMenuTTI.MenuItems.Add(DTK2100);
								AllCintiqSettings.AddTabletToCollection(CurrentTablet);

								myMainWindow = new TTIServer.TTISettings.MainWindow(wc21ux, CurrentTablet);
								//Setup a Label Array in the Layout Control.  Just get the Array Reference!

								break;
							case 0xF8:
								LoadedTablets[TabletIndex] = AllCintiqSettings.GetTabletSettingsForPID(PID);

								if (LoadedTablets[TabletIndex] == null)
								{
									//Initialize Tablet
									CurrentTablet = DefaultTabletSettings.GetDefaultTabletSettings();
									CurrentTablet.ModelNumber = "DTH/K-2400";
									CurrentTablet.Name = "Cintiq 24HD";
									CurrentTablet.PID = PID;
									CurrentTablet.TabletID = TabletIndex++;

									//Initialize ExpressKeys
									w24hdEKS = new ExpressKeySettings(0xF8);
									w24hdEKS.Initialize(false);
									K_Styli = new List<EMRDevice>(1);
									CurrentTablet.SetCintiqButtonSettings(w24hdEKS);
									CurrentTablet.SetCurrentPenSettings(K_Styli);
									LoadedTablets[TabletIndex] = CurrentTablet;

								}

								wc24hd = aCintiq;
								//wc24hd.PenRotateEventWithAngle += new WCintiqHID.Cintiq_K.PenCurrentRotationAngleHandler(OnPenRotationValueEvent);
								wc24hd.ExpressKeyEvent += new WCintiqHID.Cintiq_K.ExpressKeyHandler(OnExpressKeyEvent);
								wc24hd.ExpressPadEvent += new WCintiqHID.Cintiq_K.ExpressPadHandler(OnExpressPadEvent);
								wc24hd.PenRotateEvent += new WCintiqHID.Cintiq_K.PenRotationHandler(OnPenRotationEvent);
								wc24hd.PenProxInEvent += new WCintiqHID.Cintiq_K.PenProxInHandler(OnPenProxInEvent);
								wc24hd.PenProxOutEvent += new WCintiqHID.Cintiq_K.PenProxOutHandler(OnPenProxOutEvent);
								wc24hd.PenRotateEventWithAngle += new WCintiqHID.Cintiq_K.PenCurrentRotationAngleHandler(OnPenRotationValueEvent);
								w24hdEKS = LoadedTablets[TabletIndex].GetCintiqButtonSettings();
								K_Styli = LoadedTablets[TabletIndex].GetPensProxedIn();

								if (K_Styli == null)
								{

									K_Styli = new List<EMRDevice>(1);
									LoadedTablets[TabletIndex].SetCurrentPenSettings(K_Styli);
								}

								WCintiqHID.TouchInterface_Class myTTClass = TTInit.Find_TouchInterface(0xF6);
								myTTClass.EnableTouchScreen(true);

								w24hdEKS = new ExpressKeySettings(0xF8);
								w24hdEKS.Initialize(false);

								CurrentTablet.SetCintiqReference(wc24hd);
								CurrentTablet.SetCintiqButtonSettings(w24hdEKS);
								CurrentTablet.SetCurrentPenSettings(K_Styli);

								System.Windows.Forms.MenuItem DTK2400 = new System.Windows.Forms.MenuItem("Cintiq 24HD (DTH-2400)");
								System.Windows.Forms.MenuItem DTK2400Extras = new System.Windows.Forms.MenuItem("Disable Tablet Input");
								System.Windows.Forms.MenuItem DTK2400Touch = new System.Windows.Forms.MenuItem("Disable Touch Input");
								System.Windows.Forms.MenuItem DTK2400Extras2 = new System.Windows.Forms.MenuItem("Diagnostics");
								GroupButtonArmed = new bool[] {true, true};

								DTK2400.MenuItems.Add(DTK2400Extras);
								DTK2400.MenuItems.Add(DTK2400Extras2);
								DTK2400.MenuItems.Add(DTK2400Touch);
								ContextMenuTTI.MenuItems.Add(DTK2400);
								AllCintiqSettings.AddTabletToCollection(CurrentTablet);
								myRotationMenu = new RotationMenu(stopLabels.Count, stopLabels);
								myMainWindow = new TTIServer.TTISettings.MainWindow(wc24hd, CurrentTablet);

								break;
							default:
								break;

						}
					}

					PASWindowClass myPASWindow  = null;
					if (SystemParameters.VirtualScreenHeight < 2800)
						myPASWindow = new PASWindowClass(wc24hd);
					//myRotationMenu.Visibility = Visibility.Visible;

				}



			}



			protected override void OnExit(ExitEventArgs e)
			{
				base.OnExit(e);



			}

			void ExitServer_Select(object sender, EventArgs e)
			{
				TTINotify.Visible = false;
				TTINotify = null;



				CintiqSettinsCollectionLoader.SaveTTISettings(AllCintiqSettings);

				System.Environment.Exit(0);
			}

			void OpenSettingsMenu_Select(object sender, EventArgs e)
			{
				
				myMainWindow.Visibility = Visibility.Visible;

			}

			void TTINotify_DoubleClick(object sender, EventArgs e)
			{
				
			}


			void OnExpressKeyEvent(ExpressKeyVals.WhichSide side, ExpressKeyVals.ExpressKeys ek, ExpressKeyVals.EKButtonState bs)
			{
				int ws = (int)side;
				int buttonVal = ExpressKeyVals.ButtonValue(ek);

				if (bs == ExpressKeyVals.EKButtonState.Down)
				{
					//myRotationMenu.HILO = true;

					switch (w24hdEKS.TabletEKs[ws, buttonVal].EKAction)
					{
						case ExpressKeySettings.ExpressKeyActionType.Keystroke:
							switch (w24hdEKS.TabletEKs[ws, buttonVal].KeyCombo.Length)
							{
								case 1:
									WindowsInput.InputSimulator.SimulateKeyDown(w24hdEKS.TabletEKs[ws, buttonVal].KeyCombo[0]);
									break;
								case 2:
									InputSimulator.SimulateModifiedKeyStroke(w24hdEKS.TabletEKs[ws, buttonVal].KeyCombo[0], w24hdEKS.TabletEKs[ws, buttonVal].KeyCombo[1]);
									break;
								default:
									break;
							}
							break;
						case ExpressKeySettings.ExpressKeyActionType.Momentary:
							ProcessMomentaryData(w24hdEKS.TabletEKs[ws, buttonVal].MomentaryData, bs);
							break;
						case ExpressKeySettings.ExpressKeyActionType.RotationMenu:
							myRotationMenu.ShowRotationMenu(true);
							break;
						case ExpressKeySettings.ExpressKeyActionType.ExpressGroup:
							//sbyte LEDSide;

							if (GroupButtonArmed[ws])
							{
								if (ws == 0)
									LED_L++;
								else
									LED_R++;

								if (LED_L > 0x7)
									LED_L = 4;

								if (LED_R > 0x7)
									LED_R = 4;

								byte LED_VAL = LED_L;
								LED_VAL &= 0xF;
								LED_VAL = (byte)(LED_VAL << 4);
								LED_VAL |= LED_R;
								//Console.WriteLine("Sending {0} to the driver", LED_VAL);
								wc24hd.SetCintiqLights(LED_VAL);
								GroupButtonArmed[ws] = false;
							}
							break;
					}
				}
				else if (bs == ExpressKeyVals.EKButtonState.Up)
				{
					//myRotationMenu.HILO = false;

					switch (w24hdEKS.TabletEKs[ws, buttonVal].EKAction)
					{
						case ExpressKeySettings.ExpressKeyActionType.Keystroke:
							switch (w24hdEKS.TabletEKs[ws, buttonVal].KeyCombo.Length)
							{

								case 1:
									WindowsInput.InputSimulator.SimulateKeyUp(w24hdEKS.TabletEKs[ws, buttonVal].KeyCombo[0]);
									break;
								case 2:
									//SendInput wrapper doesn't need a key up!
									break;
									
								default:
									break;
							}
							break;
						case ExpressKeySettings.ExpressKeyActionType.Momentary:
							ProcessMomentaryData(w24hdEKS.TabletEKs[ws, buttonVal].MomentaryData, bs);
							break;
						case ExpressKeySettings.ExpressKeyActionType.ExpressGroup:
							GroupButtonArmed[ws] = true;
							break;
						case ExpressKeySettings.ExpressKeyActionType.RotationMenu:
							myRotationMenu.ShowRotationMenu(false);
							break;
					}
				}





			}



			static ExpressKeyVals.ExpressPad epLast;
			static bool PadScrolling;


			void OnPenRotationValueEvent(float angle, float distance)
			{
				//Console.WriteLine("Got a rotate Value event!");

				if (myRotationMenu != null)
					if (myRotationMenu.IsVisible == true)
					{
						myRotationMenu.setRotationAngle(angle, distance);
					}



			}

			void OnPenRotationEvent(ExpressKeyVals.RotationDirection rotDir)
			{

				if (PenRotationEnabled)
					switch (rotDir)
					{
						case ExpressKeyVals.RotationDirection.Left:
							OnPenLeftRotation();
							break;
						case ExpressKeyVals.RotationDirection.Right:
							OnPenRightRotation();
							break;

					}



			}

			void OnPenRotationEvent(clrWIntuosHID.WIntuos4.RotationDirection rotDir)
			{

				if (PenRotationEnabled)
					switch (rotDir)
					{
						case clrWIntuosHID.WIntuos4.RotationDirection.Left:
							OnPenLeftRotation_Intuos();
							break;
						case clrWIntuosHID.WIntuos4.RotationDirection.Right:
							OnPenRightRotation_Intuos();
							break;

					}



			}

			void OnPenLeftRotation_Intuos()
			{

				//TODO: Switch based on Combination or just single key




			}

			void OnPenRightRotation_Intuos()
			{

				//TODO: Switch based on Combination or just single key


			}

			void OnPenLeftRotation()
			{


				//TODO: Switch based on Combination or just single key




			}

			void OnPenRightRotation()
			{


				//TODO: Switch based on Combination or just single key


			}

			//intuos touch rings
			//24HD has two touch rings!

			private sbyte ThroughOriginRotation(byte inEPVal)
			{
				if (((IntuosTRLast == 0x80) || (IntuosTRLast == 0x81)) && (inEPVal == 0xC7))
					return -1;
				else if ((IntuosTRLast == 0xC7) && ((inEPVal == 0x80) || (inEPVal == 0x81)))
					return 1;
				else
					return 0;
			}

			static bool isScrolling;
			static byte IntuosTRLast;
			void OnTouchRingEvent(byte epVal)
			{

				if (IntuosTRLast == 0)
					IntuosTRLast = epVal;

				//Account for faster speeds!
				//The Touchring Doesn't detect every turn!

				//Rotating CW 
				if (((IntuosTRLast < epVal) && (ThroughOriginRotation(epVal) == 0)) || (ThroughOriginRotation(epVal) == 1))
				{


					InputSimulator.SimulateMouseScroll(0);
					IntuosTRLast = epVal;
					isScrolling = true;
				}

				//Rotating CCW
				else if (((IntuosTRLast > epVal) && (ThroughOriginRotation(epVal) == 0)) || (ThroughOriginRotation(epVal) == -1))
				{
					InputSimulator.SimulateMouseScroll(1);
					IntuosTRLast = epVal;
					isScrolling = true;
				}

				//TouchRing Tap
				if ((epVal == 0) && (!isScrolling))
				{
					//TouchButton Thing
				}

				else if ((epVal == 0) && (isScrolling))
				{
					isScrolling = false;
				}




			}


			void OnExpressPadEvent(ExpressKeyVals.WhichSide side, ExpressKeyVals.ExpressPad ep)
			{



				if (ep != ExpressKeyVals.ExpressPad.NoTouch)
				{
					//check for adjacent bits
					if (epLast != 0)
					{
						if (((int)epLast >> 1) == (int)ep) //Moving Left bitwise -- Up Physically
						{

							//This is where I use the EPSettings to run the appropriate Action
							InputSimulator.SimulateMouseScroll(1);
							epLast = ep;
							PadScrolling = true;

						}

						if (((int)epLast << 1) == (int)ep) //Moving right Bitwise -- Down physically
						{
							InputSimulator.SimulateMouseScroll(0);
							epLast = ep;
							PadScrolling = true;

						}
					}

					epLast = ep;


				}

				if (ep == ExpressKeyVals.ExpressPad.NoTouch)
				{
					if (!PadScrolling) //At the end of a scroll across the Pads, do not execute a scroll.
					{
						if ((int)epLast < 0x100)
						{
							InputSimulator.SimulateMouseScroll(1);
							epLast = ep;
						}

						if ((int)epLast >= 0x100)
						{
							InputSimulator.SimulateMouseScroll(0);
							epLast = ep;
						}
					}
					else
					{
						PadScrolling = false;
					}
					epLast = 0;
				}





			}

			//void Cintiq_SetPenImage(String WhichImage)
			//{
			//	BitmapImage inBI;
			//	//Needs to switch to active tablet
			//	switch (WhichImage) //Need to Get the 3 other Characters XXX802 to really know Pen Type
			//	{
			//		case "GripPen":
			//			CintiqGripPen.Visibility = System.Windows.Visibility.Visible;
			//			break;
			//		case "InkPen":
			//			CintiqInkPen.Visibility = System.Windows.Visibility.Visible;
			//			break;
			//		case "ArtPen":
			//			CintiqArtPen.Visibility = System.Windows.Visibility.Visible;
			//			break;
			//		case "AirbrushPen": //Airbrush
			//			CintiqAirbrushPen.Visibility = System.Windows.Visibility.Visible;
			//			break;
			//		case "ClassicPen":
			//			CintiqClassicPen.Visibility = Visibility.Visible;
			//			break;
			//		case "LensCursor":
			//			Cintiq24HDLensCursor.Visibility = Visibility.Visible;
			//			break;
			//		case "Mouse":
			//			Cintiq24HDMouse.Visibility = Visibility.Visible;
			//			break;
			//		default:
			//			break;
			//	}
			//}


			//void SetPenImage(String WhichImage)
			//{
			//	BitmapImage inBI;

			//	switch (WhichImage) //Need to Get the 3 other Characters XXX802 to really know Pen Type
			//	{
			//		case "802":
			//		case "80C":
			//			//inBI = new BitmapImage(new Uri("Resources/LargeGripPenCustom.png", UriKind.RelativeOrAbsolute));
			//			IntuosGripPen.Visibility = System.Windows.Visibility.Visible;
			//			break;
			//		case "804":
			//		case "80A":
			//			//inBI = new BitmapImage(new Uri("Resources/LargeArtPen.png", UriKind.RelativeOrAbsolute));
			//			IntuosArtPen.Visibility = System.Windows.Visibility.Visible;
			//			break;
			//		case "806":
			//			IntuosMouse.Visibility = Visibility.Visible;
			//			break;
			//		case "006":
			//			IntuosLensCursor.Visibility = Visibility.Visible;
			//			break;
			//		case "902": //Airbrush
			//			break;
			//		default:
			//			//inBI = new BitmapImage(new Uri("Resources/GripPenPro.png"));
			//			break;
			//	}



				//PenImage.BeginInit();
				//PenImage.Source = inBI;
				//PenImage.EndInit();
			//}

			void OnPenProxInEvent(clrWIntuosHID.WIntuos4.PenInfoClass myPIC)
			{


			}

			void OnPenProxInEvent(PenInfoClass myPIC)
			{
				//bi = new BitmapImage();
				//TODO: Update the status screen with what type of pen is being used.
				EMRDevicesEqual myEMRComp = new EMRDevicesEqual();
				EMRDevice myEMRD = new EMRDevice();
				List<PenType> AvailPens = AvailalePens.AvailableKPens;

				string tmpID = myPIC.GetPenID();
				if (tmpID.EndsWith("A"))
					tmpID = tmpID.Replace('A', '2');
				if (tmpID.EndsWith("C"))
					tmpID = tmpID.Replace('C', '4');

				foreach (PenType pt in AvailPens)
				{
					if (tmpID == pt.PenID)
					{
						myEMRD.PenTypeInformation = pt;
						break;
					}

				}


				myEMRD.SerialNum = myPIC.GetSerialNumber();
				myEMRD.NickName = myEMRD.GetDefaultEMRName(tmpID);

				if (!K_Styli.Contains(myEMRD))
				{
					K_Styli.Add(myEMRD);
				}

				if (myMainWindow.Visibility == Visibility.Visible)
				{
					myMainWindow.NewPenProxedIn(myEMRD.NickName);
				}







			}

			void OnPenProxOutEvent()
			{



			}


			void ProcessMomentaryData(byte[] inData, clrWIntuosHID.WIntuos4.ButtonState bsIn)
			{
				switch (inData.Length)
				{
					case 3:
						switch (inData[0])
						{
							case 0x38:
								switch (inData[1])
								{
									case 0x30:
										switch (inData[2])
										{
											case 0x34: //804 Art Pen
												if (bsIn == clrWIntuosHID.WIntuos4.ButtonState.Down)
													PenRotationEnabled = true;
												if (bsIn == clrWIntuosHID.WIntuos4.ButtonState.Up)
													PenRotationEnabled = false;
												break;

										}

										break;

								}

								break;
						}
						break;
				}


			}


			void ProcessMomentaryData(byte[] inData, Treblotto_TabletDefs.ExpressKeyVals.EKButtonState bsIn)
			{
				switch (inData.Length)
				{
					case 3:
						switch (inData[0])
						{
							case 0x38:
								switch (inData[1])
								{
									case 0x30:
										switch (inData[2])
										{
											case 0x34: //804 Art Pen
												if (bsIn == ExpressKeyVals.EKButtonState.Down)
													PenRotationEnabled = true;
												if (bsIn == ExpressKeyVals.EKButtonState.Up)
													PenRotationEnabled = false;
												break;

										}

										break;

								}

								break;
						}
						break;
				}


			}



			// Entry point method
			//[STAThread]
			//public static void Main()
			//{
			//	TTIServerClass TTIapp = new TTIServerClass();
			//	TTIapp.Run();
			//}
		}


}
